import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

//import static java.util.concurrent.locks.AbstractQueuedSynchronizer.*;

//设计一个同步工具，只允许最多两个线程访问，超过两个线程的访问将被阻塞
class TwinsLock implements Lock {
    private final Sync sync = new Sync(2);
    // 静态内部类，用来聚合AQS，以便自定义同步器
    private static final class Sync extends AbstractQueuedSynchronizer {
        //private static final long serialVersionUID = -5179523762034025860L;
        Sync(int count) {
            if(count < 0) {
                throw new IllegalArgumentException("count must large than zero.");
            }
            //调用AQS方法设置同步状态变量
            setState(count);
        }

        public int tryAcquireShared(int reduceCount) {
            for(;;) {
                int current = getState();
                int newCount = current - reduceCount;
                // 只有在资源数 <0 或者获取成功时才返回，否则持续循尝试获取
                if (newCount<0 || compareAndSetState(current,newCount)) {
                    return newCount;
                }
            }
        }

        public boolean tryReleaseShared(int returnCount) {
            for(;;) {
                int current = getState();
                int newCount = current + returnCount;
                //CAS保证多线程释放锁的线程安全
                if (compareAndSetState(current, newCount)) {
                    return true;
                }
            }
        }
    }

    //提供给面向使用者的外部接口
    public void lock() {
        //内部调用自定义同步器实现锁
        sync.acquireShared(1);
    }

    //提供给面向使用者的外部接口
    public void unlock() {
        sync.releaseShared(1);
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public boolean tryLock() {
        return false;
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public Condition newCondition() {
        return null;
    }

}

public class Main {
    public void testTwinsLock() {
        final Lock lock = new TwinsLock();
        class Worker extends Thread {
            public void run() {
                while(true) {
                    lock.lock();
                    try {
                        Thread.sleep(1000);
                        System.out.println(currentThread().getName());
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        lock.unlock();
                    }
                }
            }
        }

        for(int i=0; i<10; i++) {
            Worker w = new Worker();
            w.setDaemon(true);
            w.start();
        }

        //每隔1秒换行
        for(int i=0; i<10; i++) {
            try {
                Thread.sleep(1000);
                System.out.println();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        Main app = new Main();
        //打印应该看到每次最多两个线程输出名字
        app.testTwinsLock();
    }
}
